#include <QCoreApplication>
#include <iostream>
#include <QString>
#include <QHash>
#include <QVector>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
#include <QDebug>
#include "tinyxml2.h"

using namespace std;
using namespace tinyxml2;

struct tagParamItem
{
    tagParamItem():msgType(-1) {}
    tagParamItem(int mType,QString p1,QString p2)
        : msgType(mType),param1(p1),param2(p2) {}

    int msgType;
    QString param1;
    QString param2;
};

QHash<QString,tagParamItem> mParamLists;

int FindSourceFiles(const QString& directoryPath, QVector<QString> &fileList,
                    bool includeSubDirectories = true)
{
    QDir dir(directoryPath);

    if (!dir.exists()) {
        qWarning() << "目录不存在:" << directoryPath;
        return -1;
    }

    QStringList nameFilters = {
        "*.h", "*.hpp", "*.hxx", "*.h++",
        "*.c", "*.cpp", "*.cxx", "*.cc", "*.c++"
    };

    QDir::Filters filters = QDir::Files | QDir::NoDotAndDotDot;
    QDirIterator::IteratorFlags flags = includeSubDirectories ?
                                            QDirIterator::Subdirectories :
                                            QDirIterator::NoIteratorFlags;

    QDirIterator it(directoryPath, nameFilters, filters, flags);

    int count = 0;
    while (it.hasNext()) {
        it.next();
        QFileInfo fileInfo = it.fileInfo();
        fileList.append(fileInfo.absoluteFilePath());
        count++;
    }

    return count;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QVector<QString> decfileList;

    //if(argc < 2) {
    //    cout << "参数不对." << endl;
    //    return 0;
    //}

    QString decPath = "/home/ou/1639game/Source";

    XMLDocument doc;

    XMLError result = doc.LoadFile(QString(QCoreApplication::applicationDirPath()+"/params.xml").toStdString().c_str());

    if (result != XML_SUCCESS) {
        cout << "无法加载 XML 文件，错误代码: " << result << endl;
        return 0;
    }

    // 获取根元素
    XMLElement* root = doc.RootElement();
    if (!root) {
        cout << "找不到根元素" << endl;
        return 0;
    }

    // 遍历所有 param 元素
    XMLElement* param = root->FirstChildElement("param");
    int count = 0;

    while (param != nullptr) {
        count++;

        const char* type = param->Attribute("type");
        const char* srcparam = param->Attribute("srcparam");
        const char* decparam = param->Attribute("decparam");

        mParamLists[srcparam] = tagParamItem(QString(type).toInt(),
                                             srcparam,
                                             decparam);

        param = param->NextSiblingElement("param");
    }

    if(FindSourceFiles(decPath,decfileList) <= 0) {
        cout << "目标目录下没有找到文件." << endl;
        return 0;
    }

    for(int i=0;i<decfileList.size();i++) {
        QString filePath = decfileList[i];

        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "Cannot open file for reading:" << filePath << file.errorString();
            return 0;
        }

        QString content,newcontent;

        while (!file.atEnd()) {
            content = file.readLine();

            QString tmpContent = content;
            QHash<QString,tagParamItem>::iterator iter = mParamLists.begin();
            for(;iter != mParamLists.end();++iter)
            {
                if((*iter).msgType == 0)
                {
                    tmpContent = tmpContent.replace((*iter).param1,(*iter).param2);
                }
                else if((*iter).msgType == 1)
                {
                    int pos1 = tmpContent.indexOf((*iter).param1);
                    if(pos1 > 0) {
                        int pos2 = tmpContent.mid(0,pos1).lastIndexOf("this");
                        if(pos2 > 0) {
                            QString firstStr = tmpContent.mid(0,pos2) + (*iter).param2 + "(";
                            int tmpstartpos = pos1+(*iter).param1.length()+2;;
                            int pos3 = tmpContent.mid(tmpstartpos).indexOf(")");
                            if(pos3 > 0) {
                                firstStr += (tmpContent.mid(tmpstartpos,pos3)+",this");
                                firstStr += tmpContent.mid(tmpstartpos+pos3);
                                tmpContent = firstStr;
                            }
                        }
                    }
                }
                else if((*iter).msgType == 2)
                {
                    int pos1 = tmpContent.indexOf((*iter).param1);
                    if(pos1 >= 0 && tmpContent.mid(0,pos1).indexOf("//") < 0)
                        tmpContent = "//" + tmpContent;
                }
            }

            newcontent += tmpContent;
        }

        file.close();

        if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
            qWarning() << "Cannot open file for writing:" << filePath << file.errorString();
            return 0;
        }

        //QTextCodec *gb2312codec = QTextCodec::codecForName("GB2312");
        //QTextCodec *utf8codec = QTextCodec::codecForName("UTF-8");
        //QString tmpContent = gb2312codec->toUnicode(newcontent.toLocal8Bit());

        file.write(newcontent.toUtf8());
        file.close();

        qDebug() << "文件:" << filePath << "转换成功.";
    }

    qDebug() << "所有文件转换完成.";

    return 1;
}
